<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>刷面试题助手</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body class="bg-gray-100">
<!-- 导航栏 -->
<nav class="bg-blue-600 p-4 text-white shadow-lg">
    <div class="container mx-auto flex justify-between items-center">
        <h1 class="text-2xl font-bold">刷面试题助手</h1>
        <ul class="flex space-x-4">
            <li><a href="#" id="getQuestionBtn" class="hover:text-blue-200">获取所有题目</a></li>
            <li><a href="#" id="addQuestionBtn" class="hover:text-blue-200">添加题目</a></li>
            <li><a href="#" id="viewWrongQuestionsBtn" class="hover:text-blue-200">查看高频错题</a></li>
            <li><a href="#" id="logoutBtn" class="hover:text-blue-200">退出登录</a></li>
        </ul>
    </div>
</nav>

<!-- 主内容区域 -->
<div class="container mx-auto p-4 flex">
    <!-- 题目列表 -->
    <div id="questionListSection" class="w-full">
        <h2 class="text-xl font-semibold mb-4">题目列表</h2>
        <ul id="questionList" class="space-y-2">
            <!-- 题目列表将通过 JavaScript 动态加载 -->
        </ul>
    </div>

    <!-- 错题侧边栏 -->
    <div id="wrongQuestionsSidebar" class="w-1/4 ml-4 hidden">
        <h2 class="text-xl font-semibold mb-4">高频错题</h2>
        <ul id="wrongQuestions" class="space-y-2">
            <!-- 错题列表将通过 JavaScript 动态加载 -->
        </ul>
    </div>
</div>

<!-- 添加题目弹窗 -->
<div id="addQuestionModal" class="modal">
    <div class="modal-content">
        <span class="close">&times;</span>
        <form id="addQuestionForm" class="mt-6 w-full max-w-md bg-white p-6 rounded-lg shadow-md">
            <input type="text" id="questionContentInput" placeholder="请输入题目内容" class="w-full px-4 py-2 mb-4 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
            <input type="text" id="questionAnswerInput" placeholder="请输入题目答案" class="w-full px-4 py-2 mb-4 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
            <input type="text" id="questionCategoryInput" placeholder="请输入题目分类" class="w-full px-4 py-2 mb-4 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
            <button type="submit" class="w-full bg-green-500 text-white px-6 py-2 rounded-lg hover:bg-green-600 transition duration-300">
                提交题目
            </button>
        </form>
    </div>
</div>

<!-- 提交答案弹窗 -->
<div id="submitAnswerModal" class="modal">
    <div class="modal-content">
        <span class="close">&times;</span>
        <div id="submitAnswerForm" class="mt-6 w-full max-w-md bg-white p-6 rounded-lg shadow-md">
            <p id="modalQuestionContent" class="text-gray-800 mb-4"></p>
            <input type="text" id="modalUserAnswer" placeholder="请在此输入您的答案" class="w-full px-4 py-2 mb-4 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
            <button id="modalSubmitBtn" class="w-full bg-blue-500 text-white px-6 py-2 rounded-lg hover:bg-blue-600 transition duration-300">
                提交答案
            </button>
            <p id="modalResultMessage" class="mt-4 text-gray-700"></p>
        </div>
    </div>
</div>

<script>
    const baseApiUrl = 'http://127.0.0.1:36985/api/v1';
    const getElement = (id) => document.getElementById(id);

    // 获取导航栏按钮
    const getQuestionBtn = getElement("getQuestionBtn");
    const addQuestionBtn = getElement("addQuestionBtn");
    const viewWrongQuestionsBtn = getElement("viewWrongQuestionsBtn");
    const logoutBtn = getElement("logoutBtn");

    // 获取内容区域
    const questionListSection = getElement("questionListSection");
    const wrongQuestionsSidebar = getElement("wrongQuestionsSidebar");

    // 获取弹窗
    const addQuestionModal = getElement("addQuestionModal");
    const submitAnswerModal = getElement("submitAnswerModal");

    // 获取弹窗关闭按钮
    const closeModalBtn = addQuestionModal.querySelector('.close');
    const closeSubmitModalBtn = submitAnswerModal.querySelector('.close');

    // 检查用户是否登录
    const user = JSON.parse(localStorage.getItem("user"));
    if (!user) {
        window.location.href = "login.html"; // 未登录则跳转到登录页面
    }

    // 获取所有题目并显示在列表中
    async function loadQuestionList() {
        try {
            console.log("Fetching questions from:", `${baseApiUrl}/questions/all`); // 调试信息
            const response = await fetch(`${baseApiUrl}/questions/all`);
            console.log("Response status:", response.status); // 调试信息
            if (!response.ok) {
                throw new Error("获取题目失败: " + response.statusText);
            }
            const questions = await response.json();
            console.log("Questions data:", questions); // 调试信息

            if (!Array.isArray(questions)) {
                throw new Error("返回的数据不是数组");
            }

            const questionList = getElement("questionList");
            questionList.innerHTML = questions.map(q => `
            <li class="p-2 border-b hover:bg-gray-200 cursor-pointer" onclick="selectQuestion('${q.id}')">
                <p class="text-gray-800">${q.content}</p>
            </li>
        `).join("");
        } catch (error) {
            console.error("获取题目失败:", error);
            alert("获取题目失败: " + error.message);
        }
    }

    // 显示错题侧边栏
    viewWrongQuestionsBtn.addEventListener("click", async (e) => {
        e.preventDefault();
        try {
            const response = await fetch(`${baseApiUrl}/questions/wrong-top10`);
            if (!response.ok) throw new Error("获取高频错题失败");
            const wrongQuestions = await response.json();

            const wrongQuestionsContainer = getElement("wrongQuestions");
            wrongQuestionsContainer.innerHTML = wrongQuestions.map(q => `
            <li class="p-2 border-b hover:bg-gray-200">
                <p class="text-gray-800">${q.content}</p>
                <p class="text-sm text-gray-600">错误次数: ${q.wrongCnt}</p>
            </li>
        `).join("");
            wrongQuestionsSidebar.classList.remove("hidden");
        } catch (error) {
            alert("获取高频错题失败：" + error.message);
        }
    });

    // 显示添加题目弹窗
    addQuestionBtn.addEventListener("click", (e) => {
        e.preventDefault();
        addQuestionModal.style.display = "block";
    });

    // 关闭添加题目弹窗
    closeModalBtn.addEventListener("click", () => {
        addQuestionModal.style.display = "none";
    });

    // 关闭提交答案弹窗
    closeSubmitModalBtn.addEventListener("click", () => {
        submitAnswerModal.style.display = "none";
    });

    // 添加题目表单提交事件
    addQuestionForm.addEventListener("submit", async (e) => {
        e.preventDefault();
        const questionContentInput = getElement("questionContentInput").value.trim();
        const questionAnswerInput = getElement("questionAnswerInput").value.trim();
        const questionCategoryInput = getElement("questionCategoryInput").value.trim();

        if (!questionContentInput || !questionAnswerInput || !questionCategoryInput) {
            alert("请输入完整的题目信息");
            return;
        }

        try {
            const response = await fetch(`${baseApiUrl}/questions/add`, {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({
                    content: questionContentInput,
                    answer: questionAnswerInput,
                    category: questionCategoryInput
                }),
            });

            if (!response.ok) throw new Error("添加题目失败");
            const result = await response.json();
            alert("题目添加成功，题目ID：" + result.id);

            // 清空输入框
            getElement("questionContentInput").value = "";
            getElement("questionAnswerInput").value = "";
            getElement("questionCategoryInput").value = "";

            // 关闭弹窗
            addQuestionModal.style.display = "none";
        } catch (error) {
            alert("添加题目失败：" + error.message);
        }
    });

    // 选择题目事件
    window.selectQuestion = async (questionId) => {
        try {
            const response = await fetch(`${baseApiUrl}/questions/${questionId}`);
            if (!response.ok) {
                throw new Error("获取题目失败: " + response.statusText);
            }
            const question = await response.json();
            if (typeof question!== 'object' ||!question.content) {
                throw new Error("返回的数据格式不正确");
            }
            // 显示题目详情
            getElement("modalQuestionContent").textContent = question.content;
            getElement("modalUserAnswer").value = "";
            getElement("modalResultMessage").textContent = "";
            submitAnswerModal.style.display = "block";
            // 存储题目ID
            getElement("submitAnswerModal").dataset.questionId = questionId;
        } catch (error) {
            console.error("获取题目失败:", error);
            alert("获取题目失败: " + error.message);
        }
    };
    // 提交答案按钮点击事件
    getElement("modalSubmitBtn").addEventListener("click", async () => {
        const userAnswer = getElement("modalUserAnswer").value.trim();
        if (!userAnswer) {
            alert("请输入答案");
            return;
        }
        // 获取题目ID
        const questionId = getElement("submitAnswerModal").dataset.questionId;
        if (!questionId) {
            alert("题目ID获取失败，请重试");
            return;
        }
        try {
            const response = await fetch(`${baseApiUrl}/questions/${questionId}/submit`, {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({ userAnswer }),
            });
            if (!response.ok) {
                throw new Error("提交答案失败: " + response.statusText);
            }
            const result = await response.json();
            // 显示结果
            getElement("modalResultMessage").textContent = result.correct
                ? "回答正确！"
                : "回答错误！正确答案是：" + result.answer;
            // 如果答案错误，更新错题计数
            if (!result.correct) {
                await fetch(`${baseApiUrl}/questions/${questionId}/wrong`, {
                    method: "POST",
                    headers: { "Content-Type": "application/json" },
                });
            }
        } catch (error) {
            console.error("提交答案失败:", error);
            alert("提交答案失败：" + error.message);
        }
    });

    // 退出登录
    logoutBtn.addEventListener("click", (e) => {
        e.preventDefault();
        localStorage.removeItem("user");
        window.location.href = "login.html";
    });

    // 初始化加载题目列表
    loadQuestionList();
</script>
</body>
</html>